package com.sskj.trafficcontrol.task;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.*;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

public class EveryHourTask {
   /* //http://www.loopon.cn/api/v1/trafficlimit/number/getCityLimit?apikey=d9194c30-1268-0137-339b-0242c0a80006&city=330100
    //大概灵澄1点钟可以获取第三方的数据信息
    public static void main(String[] args) {
        Timer timer = new Timer();
        //第一个参数是要操作的方法，第二个参数是要设定延迟的时间，第三个参数是周期的设定，每隔多长时间执行该操作,延迟10分钟后每隔30分钟执行一次
        timer.schedule(new TestTimerTask(), 0, 5*60*1000);
    }
}
class TestTimerTask extends TimerTask {
    @Override
    public void run() {
        HttpClient client = HttpClients.createDefault();

        String urlStr = "http://www.loopon.cn/api/v1/trafficlimit/number/getCityLimit?apikey=d9194c30-1268-0137-339b-0242c0a80006&city=330100";
        HttpGet get = new HttpGet(urlStr);
        try {
            HttpResponse response = client.execute(get);
            HttpEntity entity = response.getEntity();
            String result = EntityUtils.toString(entity, "UTF-8");
            System.out.println("打印输出1次");
            result = result+"----------------------"+new Date()+"-----------------------------";
            method1(result);  //文件追加
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void method1(String result) {
        FileWriter fw = null;
        try {
            //如果文件存在，则追加内容；如果文件不存在，则创建文件
            File f=new File("D:\\timeTask.txt");
            fw = new FileWriter(f, true);
        } catch (IOException e) {
            e.printStackTrace();
        }
        PrintWriter pw = new PrintWriter(fw);
        pw.println(result);
        pw.flush();
        try {
            fw.flush();
            pw.close();
            fw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }*/
}
